import {
  searchStock,
  getCategory,
  downloadFileByUrl,
  shopdelete,
  shopmsg,
  shopmodify,
  shopadd,
  login, exportDefaultByUrl
} from '@/services/erp/api';
import {PlusOutlined, QuestionCircleOutlined, DownloadOutlined, InboxOutlined, UploadOutlined} from '@ant-design/icons';
import {
  ActionType,
  ProColumns,
  ProDescriptions,
  ProFormInstance,
  ProFormUploadButton
} from '@ant-design/pro-components';
import { PageContainer, ProFormText, ProTable,} from '@ant-design/pro-components';
import {FormattedMessage, history, SelectLang, useIntl, useModel} from '@umijs/max';
import {Button, Drawer, Input, message, Tooltip, Upload, Alert, Image, Form, Modal, Popconfirm,} from 'antd';
import type {UploadProps} from 'antd';
import type {RecordKey} from '@ant-design/pro-utils/lib/useEditableArray/index'
import React, {useRef, useState, useEffect} from 'react';
import FileSaver from 'file-saver';
import request from 'umi-request';
import {get, keys, size, values} from 'lodash';
import InitialState from '@/.umi/plugin-initialState/@@initialState';
import {updateLocale} from 'moment';
import ListBody from 'antd/lib/transfer/ListBody';
import {query} from 'express';
import * as url from "url";
const {Dragger} = Upload;


const TableList: React.FC = () => {
  const {initialState, setInitialState} = useModel('@@initialState');
  const [showUpload, setShowUpload] = useState<boolean>(false);
  const [uploadSuccess, setUploadSuccess] = useState<boolean>(false);
  //添加商品窗体
  const [isModalOpen, setIsModalOpen] = useState(false);
  //详情浮层窗体
  const  [isShowDetail,setIsShowDetail] = useState<boolean>(false);
  const [shop, setShop] = useState({} as API.StockListItem);
  //编辑浮层窗体
  const [showEdit, setShowEdit] = useState<boolean>(false);

  const [storeInfo, setStoreInfo] = useState<string>("");
  const ref = useRef<ProFormInstance>();
  const [updata, setUpdata] = useState();

  const  getAll = async (params)=>{
    const  msg= await searchStock(initialState?.currentStoreKey,{
        page: params.current - 1,
        size: params.pageSize,
        ...params
      }

    );
    let a=msg.data;
    console.log(a)
    a.forEach((r,i)=>{
      r.key=i;
    })
    return {
      data: msg.data,
      success: true,
      total: msg.dataSize,

    };

  }
  //商品分类请求
  const getCata = async () => {
    const msg = await getCategory(initialState?.currentStoreKey);
    return Object.values(msg.data).map(it => {
      return {'label': it, 'value': it}
    });
  }
  // 商品删除请求
  const del = async (barcode: string | String | undefined) => {
    const msg = await shopdelete(initialState?.currentStoreKey, barcode);
    console.log(msg, '2222222222222222222');
    if(msg.status==204){
      message.success("删除成功")
    }else{
      message.error("删除失败")
    }
  }



  //修改商品请求
  const getmodify = async (data: API.Modify, id) => {
    const msg = await shopmodify(data, id, initialState?.currentStoreKey);
    console.log("33333333333333333333", msg)
    if (msg.code == 1) {
      message.success("修改成功")
    } else {
      message.error("修改失败")
    }


  }

  //添加商品请求
  const addshop = async (data: API.Addshop) => {
    const msg = await shopadd(data, initialState?.currentStoreKey);
    if (msg.code == 1) {
      message.success("添加成功")
    } else {
      message.error("添加失败")
    }
  }
  //商品详情请求

  const getshopmsg = async (barcode: string | String | undefined) => {
    const msg = await shopmsg(barcode, initialState?.currentStoreKey);
    console.log(updata)
    console.log(msg.data, '11111111111111111')
    localStorage.setItem("rowid",msg.data.id)
  }

  const [form] = Form.useForm<{ name: string; company: string }>();
  const columns: ProColumns<API.StockListItem>[] = [
    {
      title: "序号",
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: "分类",
      dataIndex: 'categoryName',
      valueType: 'select',
      request: getCata,
    },
    {
      title: "商品条码",
      dataIndex: 'barcode',
    },
    {
      title: "商品名称",
      dataIndex: 'name',
    },
    {
      title: "图片",
      valueType: 'image',
      hideInSearch: true,
      render: (text, record, _, action) => [
        <Image
          src={`https://cp.camelee.cn/pic/${record.barcode}.png`}
          width={40}
          height={40}/>
      ],
    },
    {
      title: "库存",
      dataIndex: 'stock',
      hideInSearch: true,
    },
    {
      title: "平均成本价",
      dataIndex: 'avgPurPrice',
      valueType: 'money',
      hideInSearch: true,
    },
    {
      title: "销售价",
      dataIndex: 'salePrice',
      valueType: 'money',
      hideInSearch: true,
    },
    {
      title: "毛利率",
      dataIndex: 'marginRate',
      valueType: 'percent',
      hideInSearch: true,
    },
    {
      title: "更新时间",
      dataIndex: 'updatedAt',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: "操作",
      dataIndex: 'operate',
      valueType: 'option',
      key: 'option',
      render: (text, record, _, action) => [
        <a key='editable'
           onClick={() => {
             setShop(record)
             setShowEdit(true)
             getshopmsg(record.barcode)
             const pid=localStorage.getItem("rowid")
             console.log(pid)
           }}
        >编辑
        </a>,

        <a key='detail'
           onClick={() => {
             setShop(record)
             setIsShowDetail(true)
           }}
        >详情
        </a>,
        <Popconfirm title="确认删除此项？" onCancel={()=>console.log("用户取消删除")} onConfirm={()=>del(record.barcode)}>
          <a key='delete'>删除</a>
        </Popconfirm>
      ],


    },
  ];

  const props: UploadProps = {
    name: 'file',
    action: initialState?.baseURL + `api/merchant/goods/upload/` + initialState?.currentStoreKey,
    headers: {
      Authorization: `Bearer ${initialState?.currentUser?.token}`,
    },
    onChange(info) {
      console.log(info);

      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 商品数据文件导入成功 ` + info.file.response.msg);
        setUploadSuccess(true)
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 商品数据文件导入失败 ` + info.file.response.msg);
      }
    },
  };

  const dowmloadFile = async (url: string) => {
    console.log('dowmloadFile--->', url);
    downloadFileByUrl(url).then(res => {
      console.log('dowmloadFile--dlResult->', res);
      const blob = new Blob([res], {type: "text/plain;charset=utf-8"});
      FileSaver.saveAs(blob, "商品导入示例文件.csv");
    })
  }

  const exportDefault =async (url:string)=>{
    console.log('exportDefault',url);
    exportDefaultByUrl(url).then(res=>{
      console.log(res,'exportDefault----Result')
    })
  }
  //商品资料导入的浮层表单
  const showUploadDraw = async () => {
    setShowUpload(true)
    setUploadSuccess(false)
    const name = localStorage.getItem("currentStoreName")
    setStoreInfo("门店编号：" + initialState?.currentStoreKey + " 名称：" + name)
  }

  //商品添加浮层的表单
  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = (data: API.Addshop) => {
    setIsModalOpen(false);
    addshop(data)
    form.resetFields()

  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const onFinish = (values: any) => {

  };

  const onFinishFailed = () => {
    message.warning('校验失败')
  };

  //商品编辑确认取消按钮

  const handleOk2 = (data: API.Modify,pid) => {
    var pid=localStorage.getItem("rowid")
    setShowEdit(false);
    getmodify(data,pid)
    console.log(pid,'-------------------------')
  };
  const handleCancel2 = () => {
    setShowEdit(false);
  };




  const actionRef = useRef<ActionType>();
  return (
    <>
      <PageContainer>
        <ProTable<API.StockListItem, API.PageParams>
          actionRef={actionRef}
          headerTitle="商品数据"
          rowKey="id"
          cardBordered
          search={{labelWidth: 'auto',}}
          columns={columns}
          form={form}
          formRef={ref}
          request={getAll}
          // request={async (params, sorter, filter) => {
          //   const msg = await searchStock(initialState?.currentStoreKey, {
          //       page: params.current - 1,
          //       size: params.pageSize,
          //       ...params
          //     }
          //   );
          //
          //   console.log(msg.data, '------------------------------------')
          //   return {
          //     data: msg.data,
          //     success: true,
          //     total: msg.dataSize,
          //
          //   };
          //
          //
          // }}

          toolBarRender={() => [
            <Button onClick={() => showModal()} key="primary" type="primary" shape="round" icon={<PlusOutlined/>} danger>
              商品添加
            </Button>,
            <Button onClick={() => showUploadDraw()} key="primary" type="primary" shape="round" icon={<PlusOutlined/>}
                    danger>
              商品资料导入
            </Button>,
            <Button  key="primary" type="primary" shape="round" icon={<UploadOutlined/>}
                     onClick={()=>exportDefault("https://erp.camelee.cn/shops.csv")}
                     danger>

              商品资料导出
            </Button>,
            <Button key="primary" type="primary" icon={<DownloadOutlined/>} shape="round"
                    onClick={() => dowmloadFile("https://erp.camelee.cn/goods.csv")}>
              下载示例文件
            </Button>,
            <Tooltip title="操作教程，1分钟教你怎么导入">
              <Button type="primary" shape="round" onClick={() => {
                window.open('http://erp.camelee.cn/ERP20220830.pdf');
              }}>
                导入教程
              </Button>
            </Tooltip>,
            <Tooltip title="商品资料导入数据结果：1.商品处理：商品库不存在的商品会新增进来；2.库存处理：导入的所有商品会重置为导入的库存">
              <span> 提示 <QuestionCircleOutlined/></span>
            </Tooltip>,
          ]}
        />




        <Drawer
          width={600}
          title="商品添加"
          open={isModalOpen}
          onClose={()=>{setIsModalOpen(false)}}
        >
          <Form
            name="basic"
            labelCol={{ span: 7 }}
            wrapperCol={{ span: 12 }}
            initialValues={{ remember: true }}
            onFinish={handleOk}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
            form={form}
          >

            <Form.Item
              label="商品条码"
              name="barCode"
            >
              <div >
                <Input/>
              </div>

            </Form.Item>

            <Form.Item
              label="商品名称"
              name="name"

            >
              <Input />
            </Form.Item>
            <ProFormText
              width="md"
              name="categroyName"
              label="分类"
              request={getCata}

            />
            <Form.Item
              label="售价"
              name="salePrice"

            >
              <Input />
            </Form.Item>

            <Form.Item
              label="进价"
              name="purPrice"
            >
              <Input />
            </Form.Item>

            <ProFormUploadButton
              name="upload"
              label="图片"
              max={1}
              fieldProps={{
                name: 'file',
                listType: 'picture-card',
              }}
              action="/upload.do"
            />


            <Form.Item wrapperCol={{ offset: 9, span: 16 }}>
              <Button type="primary" htmlType="submit" style={{marginRight:'50px'}} >
                确定
              </Button>
              <Button type="default" onClick={handleCancel} >
                取消
              </Button>
            </Form.Item>
          </Form>

        </Drawer>


        <Drawer
          width={600}
          title="商品导入"
          open={showUpload}
          onClose={() => {
            setShowUpload(false);
            if (uploadSuccess) {
              window.location.reload()
            }
          }}
          closable={true}
        >
          <Alert message="数据导入后不能撤回操作，请慎重操作！" type="warning" showIcon/>
          <Alert
            message="当前门店信息"
            description={storeInfo}
            type="info"
            showIcon
          />
          <Dragger  {...props} height={200}>
            <p className="ant-upload-drag-icon">
              <InboxOutlined/>
            </p>
            <p className="ant-upload-text">点击 或 拖拽文件到这里 导入 </p>
          </Dragger>,
        </Drawer>

        <Drawer
          title='商品编辑'
          width={600}
          open={showEdit}
          onClose={()=>{setShowEdit(false)}}
        >
          <Form
            name="basic"
            labelCol={{ span: 7 }}
            wrapperCol={{ span: 12 }}
            initialValues={{ remember: true }}
            onFinish={handleOk2}
            autoComplete="off"
            form={form}
          >

            <ProFormText
              width="md"
              name="categroyName"
              label="分类"
              request={getCata}
            />
            <Form.Item
              label="商品名称"
              name="name"
            >
              <Input />
            </Form.Item>

            <ProFormUploadButton
              name="upload"
              label="图片"
              max={1}
              fieldProps={{
                name: 'file',
                listType: 'picture-card',
              }}
              action="/upload.do"
            />

            <Form.Item
              label="售价"
              name="salePrice"
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="进价"
              name="purPrice"

            >
              <Input />
            </Form.Item>



            <Form.Item wrapperCol={{ offset: 9, span: 16 }}>
              <Button type="primary" htmlType="submit" style={{marginRight:'50px'}} >
                确定
              </Button>
              <Button type="default" onClick={handleCancel2} >
                取消
              </Button>
            </Form.Item>
          </Form>
        </Drawer>

        <Drawer
          title="商品详情"
          width={600}
          open={isShowDetail}
          onClose={()=>{setIsShowDetail(false)}}>
          {isShowDetail &&
          <ProDescriptions<API.StockListItem>
            columns={columns.filter(i=>i.valueType!=='option')}
            column={2}
            request={async () => ({
              data: shop || {},
            })}
          />
          }
        </Drawer>
      </PageContainer>
    </>
  );
};

export default TableList;
